package com.sunny.controller;

import com.sunny.dataobject.ProductCategory;
import com.sunny.dataobject.ProductInfo;
import com.sunny.service.CategoryService;
import com.sunny.service.ProductService;
import com.sunny.utils.ResultVOUtil;
import com.sunny.vo.ProductInfoVO;
import com.sunny.vo.ProductVO;
import com.sunny.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * 买家商品
 * Created by dell on 2018/3/29.
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {
      @Autowired
      private ProductService productService;

      @Autowired
      private CategoryService categoryService;

      @GetMapping("/list")
      public ResultVO list(){
          //1.查询所有的上架产品
          List<ProductInfo> productInfoList = productService.findUpAll();
          //2.查询类目（一次性查询）
          /*List<Integer> categoryTypeList=new ArrayList<>();
          for(ProductInfo productInfo:productInfoList){
              categoryTypeList.add(productInfo.getCategoryType());
          }*/


          //精简方法（java8,lambda表达式)
          List<Integer> categoryTypeList = productInfoList.stream()
                  .map(e -> e.getCategoryType())
                  .collect(Collectors.toList());

          List<ProductCategory> categoryList =
                  categoryService.findByCataegoryTypeIn(categoryTypeList);
          //3.数据拼装
          List<ProductVO> productVOList=new ArrayList<>();
          for(ProductCategory productCategory:categoryList){
              ProductVO productVO=new ProductVO();
              productVO.setCategoryType(productCategory.getCategoryType());
              productVO.setCategoryName(productCategory.getCategoryName());

              List<ProductInfoVO> productInfoVOList=new ArrayList<>();
              for(ProductInfo productInfo:productInfoList){
                  if(productInfo.getCategoryType().equals(productCategory.getCategoryType())){
                      ProductInfoVO productInfoVO=new ProductInfoVO();
                      BeanUtils.copyProperties(productInfo,productInfoVO);
                      productInfoVOList.add(productInfoVO);
                  }
              }
              productVO.setProductInfoVOList(productInfoVOList);
              productVOList.add(productVO);
          }

          /*ResultVO resultVO=new ResultVO();
          resultVO.setCode(0);
          resultVO.setMsg("成功");
          resultVO.setData(productVOList);*/

          return ResultVOUtil.success(productInfoList);
      }

}
